package com.emily.test.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 对象的序列化以及反序列化
 */
public class SerializeUtil {

    /**
     * 将对象进行序列化返回byte数组
     * @param object 对象
     * @return
     */
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream bos = null;
        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(object);
            byte[] bytes = bos.toByteArray();
            return bytes;
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * 将byte数组进行反序列化成对象
     * @param bytes
     * @return
     */
    public static Object unSerialize(byte[] bytes) {
        ByteArrayInputStream bas = null;
        try {
            //反序列化
            bas = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bas);
            return ois.readObject();
        } catch (Exception e) {
        }
        return null;
    }
}